package com.bys.security;

import com.bys.constant.CommonConstant;
import com.bys.exception.ServiceException;
import com.bys.security.context.AuthenticationContextHolder;
import com.bys.admin.system.dto.LoginUser;
import com.bys.admin.system.entity.SysUser;
import com.bys.admin.system.service.ISysRoleMenuService;
import com.bys.admin.system.service.ISysUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import java.util.Objects;

import static com.bys.eunm.ResultMessage.USER_PASSWORD_ERROR;
import static com.bys.eunm.ResultMessage.USER_STATUS_DISABLED;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        查询用户
        SysUser sysUser = sysUserService.getUserByUsername(username);
        if(Objects.isNull(sysUser)){
            throw new ServiceException(USER_PASSWORD_ERROR.getMessage());
        }
//       校验用户
        if(CommonConstant.DISABLED_STATUS.equals(sysUser.getStatus())){
            throw new ServiceException(USER_STATUS_DISABLED.getMessage());
        }
//       校验密码
        validatePassword(sysUser);
        return createLoginUser(sysUser);
    }

    private void validatePassword(SysUser sysUser) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        boolean matches = new BCryptPasswordEncoder().matches(password, sysUser.getPassword());
        if(!matches){
            throw new ServiceException(USER_PASSWORD_ERROR.getMessage());
        }
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getId(), user.getDeptId(), user,null);
    }
}
